import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;


public class Server1 extends Thread  {
	
	public Server1() {  
		
	} 
	
	public void run() {
		
		int port = PrefProperties1.myInputPort;
		try {
			ServerSocket ss = new ServerSocket(port); 
			while(true){
				 
				Socket s = ss.accept();  
				InputStream is = s.getInputStream();  
				ObjectInputStream ois = new ObjectInputStream(is);  
				FileObject fo = (FileObject)ois.readObject();
				
				switch(fo.flag)
				{
					case 0:
						storeFileObject(fo);
						break;
						
					case 1:
						backUpDemand(fo);
						break;
						
					case 2:
						backUpResponse(fo);
						break;
				}
				
				is.close();  
				s.close();	
			}
		}
		catch(Exception e){e.printStackTrace();}  
	}
	
	private void backUpDemand(FileObject fo)
	{
		System.out.println("SERVER - Back-up demand received.");
		File pathDoctor = new File(PrefProperties1.workingDirectory+"/store/"+fo.doctorName+"/");
		Client cl;
		
		try {
			for (final File fileEntry : pathDoctor.listFiles()) {
				
				if(fileEntry!=null){
					if(!PrefProperties1.demoMode){
						cl=new Client(new Callback(){
							@Override
							public void callback() {
								System.out.println("CLIENT - "+fileEntry.getName()+" has been sent. (BACK-UP)");
							}}, new FileObject(PrefProperties1.login,2,fileEntry.getAbsolutePath()),"localhost", fo.port);
						
						cl.run();
					}
				}
				
			}
		} catch (NullPointerException ex) {
			System.out.println("Folder path not found !");
		}
	}
	
	private void backUpResponse(FileObject fo)
	{
		System.out.println("SERVER - Back-up response received.");
		String pathFileName = PrefProperties1.workingDirectory+
				"/.received/"+
				fo.fileName;
		fo.writeFile(pathFileName);
	}
	
	private void storeFileObject(FileObject fo) throws IOException
	{
		System.out.println("SERVER - File received : "+fo.fileName);
		
		String pathFileName = PrefProperties1.workingDirectory+
				"/store/"+
				"/"+fo.doctorName+"/"+
				fo.fileName;
		
		createDirectory(fo.doctorName);
		File storedFile = new File(pathFileName);
    	if (!storedFile.exists()) {
    		storedFile.createNewFile();
		}
		fo.writeFile(pathFileName);
	}
	
	private void createDirectory(String directory)
    {
    	File storeDir = new File(PrefProperties1.workingDirectory+"/store/");
    	File doctorDir = new File(PrefProperties1.workingDirectory+"/store/"+directory+"/");
    	if (!storeDir.exists()) {
    	    boolean result = storeDir.mkdir();  
    	}
    	if (!doctorDir.exists()) {
    	    boolean result = doctorDir.mkdir();  
    	}
    }

}
